package cn.hpclub.server.model;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

@TableBind(tableName = "sys_code_type")
public class SysCodeType extends Model<SysCodeType>{

    /**
     * 
     */
    private static final long       serialVersionUID = -2231159115941621186L;

    public static final SysCodeType dao              = new SysCodeType();

    public List<Record> getCodeType(){
        String sql = " select name, id, code, value from sys_code_type where is_deleted = 0 ";
        List<Record> list = Db.find(sql);

        return list;
    }

    public List<Record> getSysCodeTypeByCode(String code){
        String sql = " select value.* from sys_code_type type,sys_code_value value where type.code = ? and type.id=value.type_id and type.is_deleted = 0 and value.is_deleted = 0 order by value.sort asc,value.id asc";
        List<Record> list = Db.find(sql, code);
        return list;
    }
    
    public List<Record> getCodeValueByTypeCode(String code){
        String sql = " select v.code, v.value, v.name, v.sort, v.remark,t.name as type_name,t.code as type_code "
        		+ " from sys_code_type as t, sys_code_value as v "
        		+ " where t.is_deleted = 0 and v.is_deleted = 0 "
        		+ " and t.id = v.type_id and t.code = ? "
        		+ " order by v.sort asc, v.id asc ";
        List<Record> list = Db.find(sql, code);
        return list;
    }

    public String getSelect(){
        String select = " select " + " (select user_name from sys_user u where t.created_by = u.id) as creator, "
                + " (select user_name from sys_user u where t.last_updated_by = u.id) as updator, " + " t.* ";

        return select;
    }

    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = " from sys_code_type as t where 1=1 ";

        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by t.name asc ";

        return sqlExceptSelect;
    }

    private String buildQuery(Entry<String, String> item){
        String sql = "";
        if(item.getKey().equals("name")){
            sql += " and t.name like '%" + item.getValue() + "%' ";
        } else if(item.getKey().equals("code")){
            sql += " and t.code like '%" + item.getValue() + "%' ";
        } else if(item.getKey().equals("value")){
            sql += " and t.value like '%" + item.getValue() + "%' ";
        }else if(item.getKey().equals("is_deleted") && !"-1".equals(item.getValue())){
            sql += " and t.is_deleted = " + item.getValue();
        }

        return sql;
    }
}
